package com.newvpn.fastbest.zenith.activity;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.newvpn.fastbest.zenith.R;
import com.newvpn.fastbest.zenith.presenter.AdPresenter;
import com.newvpn.fastbest.zenith.presenter.VPNDetailInfo;
import com.newvpn.fastbest.zenith.beans.netbeans.BaseResponse;
import com.newvpn.fastbest.zenith.beans.netbeans.EncryBean;
import com.newvpn.fastbest.zenith.beans.netbeans.VpnInfo;
import com.newvpn.fastbest.zenith.net.NetService;
import com.newvpn.fastbest.zenith.presenter.VPNPresenter;
import com.newvpn.fastbest.zenith.presenter.VPNReulst;
import com.newvpn.fastbest.zenith.utils.AdSwith;
import com.newvpn.fastbest.zenith.utils.DecryptUtils;
import com.newvpn.fastbest.zenith.utils.ToastUtils;
import com.newvpn.fastbest.zenith.utils.VLog;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;


public class VActivity extends BaseActivity {

    private RecyclerView recyclerView;
    private VPNsAdapter appsAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v_activity_vpns);
        initViews();
        loadDatas(false);
    }

    @SuppressLint("CheckResult")
    private void loadDatas(boolean showAd) {
        showLoading();
        if (showAd) {
            AdPresenter.INSTANCE.loadAD(VActivity.this, "", null, System.currentTimeMillis(), 3 * 1000);
        }
        if (!showAd) {
            List<VpnInfo> list = VPNPresenter.INSTANCE.getAllList();
            if (list !=null){
                afterGetVpnList(list);
                return;
            }
        }
        NetService.INSTANCE.getVPNList().subscribe(new Consumer<BaseResponse<EncryBean>>() {
            @Override
            public void accept(BaseResponse<EncryBean> encryBeanBaseResponse) throws Throwable {
                EncryBean data = encryBeanBaseResponse.result;
                String passwordDecrypt = DecryptUtils.decodeRSA(data.password);
                String info = DecryptUtils.decodeAES(passwordDecrypt, data.content);//"Ho8GkZqbZfGmILvU"
                Gson gson = new Gson();
                List<VpnInfo> list = gson.fromJson(info, new com.google.gson.reflect.TypeToken<List<VpnInfo>>() {
                }.getType());
                VPNPresenter.INSTANCE.setAllList(list);
                afterGetVpnList(list);

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Throwable {
                throwable.printStackTrace();
                ToastUtils.show(R.string.try_again);
                endLoading();
            }
        });
    }

    private void afterGetVpnList( List<VpnInfo> list){
        List<VPNDetailInfo> appInfos = new ArrayList<>();
        VPNDetailInfo topVpnInfo = new VPNDetailInfo();
        topVpnInfo.serverName = getString(R.string.auto1);
        topVpnInfo.countryName = getString(R.string.auto2);
        appInfos.add(topVpnInfo);
        VPNDetailInfo slectVpnDetailInfo = VPNPresenter.INSTANCE.getSelectVPNDetail();
        int select = 0;
        for (VpnInfo vpnInfo : list) {
            for (VpnInfo.Server server : vpnInfo.server) {
                VPNDetailInfo vpnDetailInfo = new VPNDetailInfo();
                vpnDetailInfo.serverName = server.serverName;
                vpnDetailInfo.countryName = vpnInfo.countryName;
                vpnDetailInfo.iconUrl = vpnInfo.iconUrl;
                vpnDetailInfo.nodeId = vpnInfo.nodeId;
                vpnDetailInfo.serverId = server.serverId;
                vpnDetailInfo.serverIp = server.serverIp;
                vpnDetailInfo.serverPort = server.serverPort;
                appInfos.add(vpnDetailInfo);
                if (slectVpnDetailInfo != null && !TextUtils.isEmpty(vpnDetailInfo.serverId)
                        && !TextUtils.isEmpty(vpnDetailInfo.nodeId)) {
                    if (vpnDetailInfo.serverId.equals(slectVpnDetailInfo.serverId) &&
                            vpnDetailInfo.nodeId.equals(slectVpnDetailInfo.nodeId)) {
                        select = appInfos.size() - 1;
                    }
                }
            }
        }
        appsAdapter = new VPNsAdapter(select);
        recyclerView.setLayoutManager(new LinearLayoutManager(VActivity.this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(appsAdapter);
        appsAdapter.setList(appInfos);
        endLoading();
    }

    private void initViews() {
        findViewById(R.id.ivBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.ivRefresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                VLog.event("Refresh_List");
                boolean showAd = true;
                if (AdSwith.hideAdAfterRefreshVPN){
                    showAd = false;
                }
                loadDatas(showAd);
            }
        });
        recyclerView = findViewById(R.id.recyclerView);
    }


    private class VPNsAdapter extends RecyclerView.Adapter<VPNsAdapter.VPNViewHolder> {
        private List<VPNDetailInfo> VPNs;
        private int select;

        VPNsAdapter(int select) {
            this.select = select;
        }

        @Override
        public VPNsAdapter.VPNViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.v_item_vpn, parent, false);
            return new VPNViewHolder(view);
        }

        @Override
        public void onBindViewHolder(VPNsAdapter.VPNViewHolder holder, int position) {
            VPNDetailInfo detailInfo = VPNs.get(position);
            holder.vpnCountry.setText(detailInfo.countryName);
            holder.vpnName.setText(detailInfo.serverName);
            holder.vpnStatus.setVisibility(select == position ? View.VISIBLE : View.INVISIBLE);
            final int pos = position;
            holder.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (select == pos) {
                        return;
                    }
                    int status = VPNPresenter.INSTANCE.getVPNStatus();
                    if (status == VPNReulst.STATE_CONNECTING ||
                            status == VPNReulst.STATE_CONNECT_NEXT ||
                            status == VPNReulst.STATE_CONNECTED_PRE ||
                            status == VPNReulst.STATE_CONNECTED_LOADADING) {
ToastUtils.show(R.string.connecting_trynext);
                        return;
                    }
                    VLog.event("Change_Location");
                    select = pos;
                    VPNPresenter.INSTANCE.setSelectVPNDetail(detailInfo);
                    VPNPresenter.INSTANCE.setNeedReconnect(true);
                    notifyDataSetChanged();
                    finish();
                }
            });
            if (TextUtils.isEmpty(detailInfo.iconUrl)) {
                holder.vpnIcon.setImageResource(R.drawable.v_nodeselect);
            } else {
                Glide.with(getApplicationContext()) // 使用当前上下文，对于 Fragment，使用 getActivity() 或者 requireActivity()
                        .load(detailInfo.iconUrl)
                        .placeholder(R.drawable.bg_circle) // 加载中的占位图
                        .error(R.drawable.bg_circle)
                        .into(holder.vpnIcon);
            }
        }

        @Override
        public int getItemCount() {
            if (VPNs == null) {
                return 0;
            }
            return VPNs.size();
        }

        public void setList(List<VPNDetailInfo> appInfos) {
            VPNs = appInfos;
        }

        class VPNViewHolder extends RecyclerView.ViewHolder {
            ImageView vpnIcon;
            TextView vpnName, vpnCountry;
            ImageView vpnStatus;
            View rootView;

            VPNViewHolder(View itemView) {
                super(itemView);
                rootView = itemView.findViewById(R.id.rootView);
                vpnIcon = itemView.findViewById(R.id.vpnIcon);
                vpnName = itemView.findViewById(R.id.vpnName);
                vpnCountry = itemView.findViewById(R.id.vpnCountry);
                vpnStatus = itemView.findViewById(R.id.vpnStatus);
            }
        }
    }

}
